﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.HtmlHelpers;
using Newtonsoft.Json;
using WebMatrix.WebData;

namespace DuocThaiBinh.Controllers
{
    public class DVCCController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        //
        // GET: /DVCC/
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,Staff")]
        public JsonResult IndexGet()
        {
            int currentCuaHangID = GetCurrentCuaHangID();
            var dvccs = db.DVCCs.OrderBy(p => p.MaDVCC).Where(p => p.MaDVCC != null && p.CuaHangID == currentCuaHangID && p.Status).ToList();

            return Json(new
            {
                data = dvccs.Select(x => new { MaDVCC = x.MaDVCC, TenDVCC = x.TenDVCC, TongNo = x.TongNo, ID = x.ID })
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetDVCCsById(string valueSearch)
        {
            DVCC dvcc = db.DVCCs.Find(Convert.ToInt32(valueSearch));
            var userInCuaHang = dvcc.CuaHang.UserInCuaHangs.Where(u => u.UserId == WebSecurity.GetUserId(User.Identity.Name));
            if (userInCuaHang.Count() != 1)
            {
                return null;
            }

            string list = Convert.ToString(dvcc.ID + ";#" + dvcc.MaDVCC + ";#" + dvcc.TenDVCC + ";#" + dvcc.DiaChi);
            //list.Add(Convert.ToString(sp.GiaNhap + ";#" + sp.DonVi));            
            return Json(new { KhachHangDetail = list });
        }

        [HttpPost]
        public JsonResult GetTableDVCCById(string valueSearch)
        {
            int cuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            string tableContent = string.Empty;
            List<DVCC> list = new List<DVCC>();
            if (!string.IsNullOrEmpty(valueSearch))
            {
                list = db.DVCCs.Where(p => p.MaDVCC.Contains(valueSearch) && p.CuaHangID == cuaHangID).Take(20).ToList();
            }
            else
            {
                list = db.DVCCs.Take(20).ToList();
            }

            if (list != null && list.Count() > 0)
            {
                foreach (DVCC dvcc in list)
                {
                    tableContent += "<tr><td><input type='button' value='Chọn' id='" + dvcc.ID + "' class='btnChon' onclick='SelectKH(" + dvcc.ID + ")'</td><td>" + dvcc.TenDVCC + "</td><td><span>" + dvcc.MaDVCC + "</span></td><td><span>" + dvcc.DiaChi + "</span></td></td><td><span>" + dvcc.SDT + "</span></td></tr>";
                }
            }

            return Json(new { ProductDetail = tableContent });
        }

        public JsonResult AATest(string id)
        {
            int cuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var dvccs = db.DVCCs.OrderBy(p => p.MaDVCC).Where(p => p.MaDVCC != null && p.CuaHangID == cuaHangID && p.Status).ToList();

            return Json(new
            {
                data = dvccs.Select(x => new { MaDVCC = x.MaDVCC, TenDVCC = x.TenDVCC, TongNo = x.TongNo, ID = x.ID })
            }, JsonRequestBehavior.AllowGet);
        }
        
        [Authorize(Roles = "Administrator,StaffXuatKho,Staff")]
        public ActionResult IndexPopUp()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,StaffXuatKho,Staff")]
        [HttpPost]
        public JsonResult IndexPopUp(int page, int rows, string sidx, string sord, bool _search, string filters)
        {
            int cuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var dvccs = db.DVCCs.OrderBy(p => p.MaDVCC).Where(p => p.MaDVCC != null && p.CuaHangID == cuaHangID && p.Status) as IEnumerable<DVCC>;

            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaDVCC": dvccs = dvccs.Where(p => p.MaDVCC.ToLower().Contains(data.ToLower())); break;
                        case "TenDVCC": dvccs = dvccs.Where(p => p.TenDVCC.ToLower().Contains(data.ToLower())); break;
                        case "DiaChi": dvccs = dvccs.Where(p => p.DiaChi.ToLower().Contains(data.ToLower())); break;
                        case "SDT": dvccs = dvccs.Where(p => p.SDT.Contains(data.ToLower())); break;
                        default: dvccs.Where(p => p.MaDVCC.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            var count = dvccs.Count<DVCC>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = dvccs.Skip(rows * (page - 1)).Take(rows).ToList();

            var result = new
            {
                total = total,
                page = page,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.MaDVCC, x.TenDVCC, x.DiaChi, x.SDT })

            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        // POST:GetDVCCById
        [HttpPost]
        public JsonResult GetDVCCById(string selectedVal)
        {
            int idDCCC = Convert.ToInt32(selectedVal);
            DVCC dvcc = db.DVCCs.Find(idDCCC);
            if (dvcc != null)
            {
                var userInCuaHang = dvcc.CuaHang.UserInCuaHangs.Where(u => u.UserId == WebSecurity.GetUserId(User.Identity.Name));
                if (userInCuaHang.Count() != 1)
                {
                    return null;
                }

                return Json(new { SoTienNoDVCC = dvcc.TongNo });
            }
            else return null;
        }

        //
        // GET: /DVCC/Create
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /DVCC/Create
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost]
        public ActionResult Create(DVCC dvcc)
        {
            if (ModelState.IsValid)
            {
                if (dvcc.TongNo == null)
                {
                    dvcc.TongNo = "0";
                }
                dvcc.Status = true;
                dvcc.CuaHangID = Convert.ToInt32(Session["CuaHangID"]);
                db.DVCCs.Add(dvcc);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(dvcc);
        }

        //
        // GET: /DVCC/Edit/5
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Edit(int id = 0)
        {
            DVCC dvcc = db.DVCCs.Find(id);
            if (dvcc == null)
            {
                return HttpNotFound();
            }

            if (dvcc.CuaHangID != GetCurrentCuaHangID())
            {
                return HttpNotFound();
            }

            return View(dvcc);
        }

        //
        // POST: /DVCC/Edit/5
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost]
        public ActionResult Edit(DVCC dvcc)
        {
            if (dvcc.CuaHangID != GetCurrentCuaHangID())
            {
                return RedirectToAction("Index");
            }

            if (ModelState.IsValid)
            {
                db.Entry(dvcc).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(dvcc);
        }

        //
        // POST: /DVCC/Delete/5
        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            DVCC dvcc = db.DVCCs.Find(id);
            if (dvcc.CuaHangID != GetCurrentCuaHangID())
            {
                return Json(new { msg = "failed" });
            }

            dvcc.Status = false;
            db.Entry(dvcc).State = EntityState.Modified;
            db.SaveChanges();
            return Json(new { msg = "success" });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}